package com.woniuxy.light_smart.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.light_smart.dto.ApplicationDto;
import com.woniuxy.light_smart.dto.AreaDto;
import com.woniuxy.light_smart.entity.*;
import com.woniuxy.light_smart.mapper.ApplicationRoleMapper;
import com.woniuxy.light_smart.mapper.LightPoleMapper;
import com.woniuxy.light_smart.service.ApplicationRoleService;
import com.woniuxy.light_smart.service.AreaService;
import com.woniuxy.light_smart.service.LightPoleService;
import com.woniuxy.light_smart.util.ObjectExcelRead;
import com.woniuxy.light_smart.util.ObjectExcelView;
import com.woniuxy.light_smart.util.PageData;
import com.woniuxy.light_smart.util.Result;
import com.woniuxy.light_smart.vo.AreaCountVo;
import com.woniuxy.light_smart.vo.AreaRoleVo;
import com.woniuxy.light_smart.vo.AreaVo;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@RequestMapping("area")
@RestController
public class AreaController {
    @Resource
    private ApplicationRoleService applicationRoleService;
    @Resource
    private LightPoleService lightPoleService;

    @Resource
    private AreaService areaService;

    //查出一个用户的角色和地区
    @PostMapping("/selectOneRoleAndArea")
    public Result selectOneRoleAndArea(@RequestBody User user){
        List<Integer> integers = areaService.selectAllOneRole(user.getUserId(),user.getAreaId());

        return Result.ok()
                .data("integers",integers)

                ;
    }


//查出所有的角色和地区
    @PostMapping("/selectAllRoleAndArea")
    public Result selectAllPro(@RequestBody User user){
        List<Role> allRole = areaService.selectAllRole();
        List<Area> allArea = areaService.selectAllArea();
        List<AreaVo> integers = areaService.selectAllOne(user.getUserId(),user.getAreaId());


        return Result.ok()
                .data("allArea",allArea)
                .data("allRole",allRole)
                .data("integers",integers)

                ;
    }

//    查全部的申请
        @PostMapping("/selectAppliction")
        public Result selectAppliction() {
            List<ApplicationRole> roles = applicationRoleService.selectAppRoleOne();

            return Result.ok()
                    .data("roles",roles)

                    ;
        }
    //    修改申请的状态
    @PostMapping("/updateApp")
    @Transactional
    public Result updateApp(@RequestBody() ApplicationDto applicationDto) {
        int i= applicationRoleService.updateUserRole(applicationDto);
        if(i>0){
            List<UserRole> roles =applicationRoleService.selectAllUserRole(applicationDto);
            int j=applicationRoleService.insertUserRole(roles);
            if (j>0){
                return Result.ok().data("roles",roles);
            }else {
                return Result.error();
            }

        }else {
            return Result.error();
        }

    }


//    提交一个记录插入角色申请表

    @PostMapping("/addApply")
    public Result updateUserAreaIdAnd(@RequestBody ApplicationDto applicationDto) {
        Integer i=applicationRoleService.insertOne(applicationDto);
        if (i!=-1){
            return Result.ok();
        }else {
            return Result.error();
        }

    }


    @GetMapping("")
    public Result getAll(){
        List<Area> all = areaService.getAll();
        return Result.ok().data("areaList",all);
    }


    /**
     * 从EXCEL导入到数据库
     */
    @RequestMapping(value="importExcel")
    public Result importExcel(MultipartFile file,HttpServletRequest request) throws Exception{

        if (null != file && !file.isEmpty()) {
            //执行读EXCEL操作,读出的数据导入List 2:从第2行开始；0:从第A列开始；0:第0个sheet
            List<PageData> listPd = (List) ObjectExcelRead.readExcel(file.getInputStream(), 1, 0, 0);
            for (PageData pageData : listPd) {
                Area area = new Area();
                String strId = pageData.getString("var0");
                int id=0;
                if(strId.indexOf(".")!=-1){
                    id = Integer.parseInt(strId.substring(0,strId.indexOf(".")));
                }else {
                    id = Integer.parseInt(strId);
                }
                area.setAreaId(id);
                area.setAreaName(pageData.getString("var1"));
//                user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(pageData.getString("var2")));
//                String strDeptId = pageData.getString("var2");
//                int deptId=0;
//                if(strDeptId.indexOf(".")!=-1){
//                    deptId = Integer.parseInt(strDeptId.substring(0,strDeptId.indexOf(".")));
//                }else{
//                    deptId =Integer.parseInt(strDeptId);
//                }
                area.setBackup1(pageData.getString("var2"));
                area.setBackup2(pageData.getString("var3"));
                areaService.insertSelective(area);
            }

        }
        return Result.ok("导入成功");
    }



    @RequestMapping(value = "/exportExcel")
    @CrossOrigin
    public ModelAndView exportExcel(@RequestBody AreaDto areadto) {
        ModelAndView mv = new ModelAndView();
        try {
            Map<String, Object> dataMap = new HashMap<>();
            //构造列名称
            List<String> titles = new ArrayList<>();
            titles.add("区域编号"); // 1
            titles.add("区域名称"); // 2
            titles.add("区域图片"); // 3
            titles.add("备用"); // 4

            dataMap.put("titles", titles);
            //得到被导出的数据
            List<Area> varOList = areaService.selectExportData(areadto);
            List<PageData> varList = new ArrayList<>();
            for (Area area1 : varOList) {
                PageData vpd = new PageData();
                vpd.put("var1",area1.getAreaId());
                vpd.put("var2",area1.getAreaName());
                vpd.put("var3",area1.getBackup1());
                vpd.put("var4",area1.getBackup2());


                varList.add(vpd);
            }
            dataMap.put("varList", varList);
            ObjectExcelView erv = new ObjectExcelView();
            mv = new ModelAndView(erv, dataMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mv;
    }
//    文件下载
    @GetMapping("downLoadFile")
    @CrossOrigin
    public void downLoadFile(HttpServletResponse response, @RequestParam("filename") String filename, HttpServletRequest request) {
        response.setHeader("Content-Type", "application/octet-stream");
        //下载文件路径
        System.out.println("111");
        String path = request.getServletContext().getRealPath("/upload");
        OutputStream out = null;
        try {
            //通过文件路径获得File对象(假如此路径中有一个download.pdf文件)
            File file = new File(path + File.separator + filename);
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            FileInputStream fin = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fin.read(data);
            fin.close();
            out = response.getOutputStream();
            out.write(data);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }





    /**
     * 文件上传
     *
     * @param file
     * @param request
     * @return
     */
    @RequestMapping("upload")
    public Result upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {

        //获取文件在服务器的储存位置
        String path = request.getServletContext().getRealPath("/upload");
        File filePath = new File(path);
        if (!filePath.exists() && !filePath.isDirectory()) {
            filePath.mkdir();
        }

        //获取原始文件名称(包含格式)
        String originalFileName = file.getOriginalFilename();

        //获取文件类型，以最后一个`.`为标识
        String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);

        //获取文件名称（不包含格式）
        String name = originalFileName.substring(0, originalFileName.lastIndexOf("."));

        //设置文件新名称: 当前时间+文件名称（不包含格式）
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = sdf.format(new Date());
        String fileName = date + name + "." + type;

        //在指定路径下创建一个文件
        File targetFile = new File(path, fileName);
        //将文件保存到服务器指定位置
        try {
            file.transferTo(targetFile);
            return Result.ok("http://localhost:9000/upload/" + fileName);
            //将文件在服务器的存储路径返回

        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("上传失败");
        }

    }
//  查全部带分页模糊
    @PostMapping("selectAll")
    public Result login(@RequestBody AreaDto areadto){
        PageHelper.startPage(areadto.getCurrentPage(), areadto.getPageSize());
        List<Area> areaList = areaService.selectAll2(areadto);
        PageInfo<AreaVo> pageInfo=new PageInfo(areaList);
        List<Role> roleList= areaService.selectAllRole();
        List<AreaVo> areaListVo = areaService.selectAllUser();
        List<AreaCountVo> areaCountVos= areaService.selectAllUserCounte();
        List<LightPole> sele = lightPoleService.sele();

        return Result.ok()
                    .data("areaList",areaList)
                    .data("total",pageInfo.getTotal())
                    .data("areaUser",areaListVo)
                    .data("roleList",roleList)
                    .data("areaCount",areaCountVos)
                     .data("sele",sele)
                 ;


    }




//    添加一个区域
    @PostMapping("")
    public Result add(@RequestBody Area Area){
        int i = areaService.insertSelective(Area);
        if(i>0){
            return Result.ok();
        }else {
            return Result.error();
        }
    }
//修改一个区域
    @PutMapping
    public Result update(@RequestBody Area Area){
        int i = areaService.updateByPrimaryKeySelective(Area);
        if(i>0){
            return Result.ok();
        }else {
            return Result.error();
        }
    }
//查询一个区域通过id
    @GetMapping(value = "{areaid}")
    public Result selectOne(@PathVariable long areaid){
        Area area = areaService.selectByPrimaryKey(areaid);
        if(area!=null){
            return Result.ok().data("area",area );
        }else {
            return Result.error();
        }
    }


//删除一个区域通过id
    @DeleteMapping(value = "{areaid}")
    public Result delect(@PathVariable long areaid){
        int i = areaService.deleteByPrimaryKey(areaid);
        if(i>0){
            return Result.ok();
        }else {
            return Result.error();
        }
    }
}
